package com.quyunshuo.module.home.room.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.quyunshuo.module.home.music.Music
import com.quyunshuo.module.home.room.entity.MusicEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface MusicDao {
    // 插入音乐（自动设置创建时间）
    @Insert
    suspend fun insert(music: MusicEntity)

    // 更新音乐信息（不更新创建时间）
    @Update
    suspend fun update(music: MusicEntity)

    // 获取所有音乐（按创建时间倒序）
    @Query("SELECT * FROM music ORDER BY createdAt DESC")
    fun getAll(): Flow<List<MusicEntity>>

    // 根据ID获取音乐
    @Query("SELECT * FROM music WHERE id = :id")
    suspend fun getById(id: Long): MusicEntity?

    // 获取最近播放的音乐（按播放时间倒序）
    @Query("SELECT * FROM music WHERE lastPlayed > 0 ORDER BY lastPlayed DESC LIMIT :limit")
     fun getRecentlyPlayed(limit: Int = 50): Flow<List<MusicEntity>>

    // 获取最新添加的音乐（按创建时间倒序）
    @Query("SELECT * FROM music ORDER BY createdAt DESC LIMIT :limit")
    suspend fun getRecentlyAdded(limit: Int = 50): List<MusicEntity>

    // 更新播放记录
    @Query("UPDATE music SET lastPlayed = :timestamp, playCount = playCount + 1 WHERE id = :id")
    suspend fun updatePlayRecord(id: Long, timestamp: Long)

    // 删除音乐
    @Query("DELETE FROM music WHERE id = :id")
    suspend fun delete(id: Long)

    // 检查音乐是否存在
    @Query("SELECT EXISTS(SELECT 1 FROM music WHERE id = :id)")
    suspend fun exists(id: Long): Boolean
    
    // 根据创建时间范围查询
    @Query("SELECT * FROM music WHERE createdAt BETWEEN :start AND :end ORDER BY createdAt DESC")
    suspend fun getByDateRange(start: Long, end: Long): List<MusicEntity>

    // 插入或更新音乐
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrUpdate(music: MusicEntity)
}